import { store } from '@/store'
import { defineStore } from 'pinia'
import * as CartApi from '@/api/shop/trade/cart'
import { fenToYuan } from '@/utils'

// const { push } = useRouter() // 路由跳转
/** 门店会员信息 */
import { useShopUserStoreWithOut } from '@/store/modules/shop/user'
const shopUserStore = useShopUserStoreWithOut()

/** 密码键盘信息 */
import { useShopKeyboardWithOut } from './keyBoard'
const shopKeyboard = useShopKeyboardWithOut()
const message = useMessage() // 消息弹窗

declare interface ShopCartVO {
  itemsList: EmptyArrayType //购物车商品列表
  totalOriginalPrice: number //订单金额
  itemsNum: number //购物车商品数

  orderId: string | undefined //订单号
  totalNumber: number //商品总数

  orderPayload: any
}

export const useShopCartStore = defineStore('shop-cart', {
  state: (): ShopCartVO => ({
    itemsList: [], //购物车商品列表
    totalOriginalPrice: 0, //订单金额
    itemsNum: 0, //购物车商品数

    orderId: undefined, //订单号
    totalNumber: 0, //商品总数

    orderPayload: {} //订单支付加载信息
  }),
  getters: {
    getCartNumber(): number {
      return this.itemsList.length
    }, //购物车商品数量
    getTotalOriginalPrice(state): string {
      let totalOriginalPrice = 0
      state.itemsList.forEach((item) => {
        totalOriginalPrice += item.count * item.sku.price
      })
      return fenToYuan(totalOriginalPrice)
    },
    getTotalNumber(state): number {
      let total = 0
      state.itemsList.forEach((item) => {
        total += item.count
      })
      return total
    }, //购物车商品种类

    getCartList(): EmptyArrayType {
      return this.itemsList
    },
    getOrderPayload(): any {
      return this.orderPayload
    }, //获取订单支付信息

    getOrderId(): any {
      return this.orderId
    }
  },
  actions: {
    // 获取购物车列表
    async getList() {
      const cartParams = {
        userId: shopUserStore.getUser.id
      }
      try {
        const data = await CartApi.getCartList(cartParams)
        this.itemsList = data.validList
        this.orderId = data.no
        this.setOrderPayload(this.itemsList)
      } finally {
      }
    },

    /** 销售 加入购物车 */
    async addCart(cartItem: CartApi.cartItemVO) {
      if (!shopUserStore.getUser.id) {
        message.error('请先选择会员')

        return
      }
      try {
        const cartParams = {
          skuId: cartItem.skuId,
          count: cartItem.goods_num,
          userId: shopUserStore.getUser.id
        }
        await CartApi.addCart(cartParams)
        message.success('加入购物车成功')
        await this.getList()
      } finally {
      }
    },
    /** 销售 赠品加入购物车 */
    async addCartGiveGoods(cartItem: CartApi.cartItemVO) {
      if (!shopUserStore.getUser.id) {
        message.error('请先选择会员')

        return
      }
      try {
        const cartParams = {
          skuId: cartItem.skuId,
          count: cartItem.goods_num,
          userId: shopUserStore.getUser.id,
          sales: true
        }
        await CartApi.addCart(cartParams)
        message.success('加入购物车成功')
        await this.getList()
      } finally {
      }
    },
    /** 销售 更新购物车 */
    async updateCart(cartParams: any) {
      try {
        cartParams.userId = shopUserStore.getUser.id
        await CartApi.updateCartCount(cartParams)
        await this.getList()
      } finally {
      }
    },
    /** 销售 删除购物车 */
    async deletCart(id: any) {
      try {
        const cartParams = {
          userId: shopUserStore.getUser.id,
          ids: id
        }
        await CartApi.deleteCart(cartParams)
        message.success('删除成功')
        await this.getList()
      } finally {
      }
    },
    /** 设置 订单支付信息 */
    setOrderPayload(list) {
      const items = [] as EmptyArrayType
      list.map((item) => {
        items.push({
          skuId: item.sku.skuId,
          count: item.count,
          cartId: item.id,
          categoryId: item.spu.categoryId,
          sales: item.sales, //是否赠送
          spuType: item.spu.spuType, //spuType
          sku: item.sku
        })
      })
      this.orderPayload = {
        items: items
      }
    },

    restSalesStateData() {
      this.$reset()
    }, //清除销售信息

    handleOpenCodeKeyboard() {
      const codeKeyboardConfig = {
        dialogVisible: true,
        title: '请输入密码', //数字键盘弹框的标题
        keyboardValue: ''
      }
      shopKeyboard.setCodeKeyboardConfig(codeKeyboardConfig)
    }, //打开密码框
    closeCodeKeyBoard() {
      const config = {
        dialogVisible: false,
        title: '请输入密码', //数字键盘弹框的标题
        keyboardValue: ''
      }
      shopKeyboard.setCodeKeyboardConfig(config)
    }
  }
})
export const useShopCartStoreWithOut = () => {
  return useShopCartStore(store)
}
